package edu.gyc.collectionhomework;

import java.util.*;

public class Test {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("ccc");
        list.add("ddd");
        list.add("aaa");
        list.add("aaa");
        list.add("ffff");
        list.add("heima");
        list.add("bbbb");
        list.add("aaa");

        System.out.println("list:"+list);

        System.out.println("直接使用TreeSet排序");
        TreeSet<String> treeSet = new TreeSet<>();
        treeSet.addAll(list);
        ArrayList<String> list1 = new ArrayList<>();
        list1.addAll(treeSet);
        System.out.println("list1:"+list1);
        System.out.println("list1中重复元素丢失");
        System.out.println(list);

        System.out.println("使用自定义比较器排序：");
        sort(list);
        System.out.println("list:"+list);


    }
    //使用TreeSet(Comparator<? super E> comparator),传递给TreeSet一个自定义比较器Comparator
    public static void sort(List<String> list) {
        TreeSet<String> ts = new TreeSet<String>(new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                int num = s1.compareTo(s2);    //比较内容为主要条件
                return num == 0 ? 1 : num; //保留重复
            }
        });

        ts.addAll(list);
        list.clear();
        list.addAll(ts);
    }
}
